﻿/*
 * os_thread.cpp
 *
 *  Created on: 2016年12月13日
 *  Author: wangwei
 */
#include "xthread.h"

lxThread::lxThread(void)
{

	m_hThread = 0;
	m_bThreadEnd = true;
}

lxThread::~lxThread(void)
{
	Join();
}

int32 lxThread::Start()
{
	if (0 == m_hThread) {
		m_bThreadEnd = false;
#ifndef WIN32
		if (pthread_create(&m_hThread, 0, ThreadProc, this)) {
			m_hThread = 0;
			return -1;
		}
#else
		m_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, this, 0, NULL);
		if (NULL == m_hThread) {
			return -1;
		}
#endif
	}
	return 0;
}
void lxThread::End()
{
	m_bThreadEnd = true;
}

void lxThread::Join()
{
	if (m_hThread) {
		m_bThreadEnd = true;
#ifdef WIN32
		WaitForSingleObject(m_hThread, INFINITE);
		CloseHandle(m_hThread);
#else
		pthread_join(m_hThread, 0);
#endif
		m_hThread = 0;
	}
}

void lxThread::Run(void)
{

}

#ifndef WIN32
void* lxThread::ThreadProc(void* pParam)
#else
unsigned WINAPI lxThread::ThreadProc(void* pParam)
#endif
{
	((lxThread*)pParam)->Run();
#ifndef WIN32
	pthread_exit(0);
#else
	_endthreadex(0);
#endif
	return 0;
}

bool lxThread::IsRun()
{
	return !m_bThreadEnd;
}

#ifndef WIN32
int	lxThread::Start(void* (*ThreadFun)(void*), void* lpParam)
#else
int	lxThread::Start(_beginthreadex_proc_type ThreadFun, void* lpParam)
#endif // WIN32
{
	if (0 == m_hThread) {
		m_bThreadEnd = false;
#ifndef WIN32
		if (pthread_create(&m_hThread, 0, ThreadFun, lpParam)) {
			m_hThread = 0;
			return -1;
		}
#else
		m_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, lpParam, 0, NULL);
		if (NULL == m_hThread) {
			return -1;
		}
#endif
	}
	return 0;
}
